package cn.tsinghua.comsmacitccntsinghua.httpservice;

import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.tsinghua.comsmacitccntsinghua.DeviceInfo;
import cn.tsinghua.comsmacitccntsinghua.bean.BaseDataInfo;
import cn.tsinghua.comsmacitccntsinghua.bean.EquipmentStatusBean;
import cn.tsinghua.comsmacitccntsinghua.bean.EventReportBean;
import cn.tsinghua.comsmacitccntsinghua.bean.GPSBean;
import cn.tsinghua.comsmacitccntsinghua.bean.UserBean;
import cn.tsinghua.comsmacitccntsinghua.bean.WarnReport;
import cn.tsinghua.comsmacitccntsinghua.bean.WeightBean;
import cn.tsinghua.comsmacitccntsinghua.tsinterface.IStringResponse;

/**
 * @Author yjl
 * @create 2021/9/10 11:00
 */
public class HttpUtil {
    private static Gson gson = new Gson();
    public static BaseDataInfo baseDataInfo = null;
    public static void getDeviceInfo(String boardId){
        Map<String,String> map = new HashMap<>();
        map.put("boardId",boardId);
        Log.d("Iddddd",boardId);
        API.getOrganizationInfo(map, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                String  errorCode = jsonObject.getString("err_code");
                if (errorCode.equals("1")){
                    Log.d("RegisterE","设备不存在");  //这边表示设备确实未注册
                    EventBus.getDefault().post("noRegister");
                }else if(errorCode.equals("0")){
                    if(result!= null && !result.equals("")){
                        baseDataInfo = gson.fromJson(result,BaseDataInfo.class);
                        DeviceInfo.setDeviceId(String.valueOf(baseDataInfo.getData().getDevice().getId()));
                        DeviceInfo.setBaseDataInfo(baseDataInfo);
                        //完成加载发信息到MainActivity更新UI
                        EventBus.getDefault().post("finish_server_data");
                    }
                }
            }
            @Override
            public void onFail(int statusCode) {

                Log.d("FFFFF","NetFFF");

                EventBus.getDefault().post("finish_server_data_error");

            }
        });

    }


    //4.投递数据接口
    public static void retrieveRes(WeightBean weightBean){

        weightBean.setDeviceId(weightBean.getDeviceId());

        weightBean.setCustomerId(weightBean.getCustomerId());

        if(DeviceInfo.customerId == null){
            Log.d("noIdPut","无账号投递");
            EventBus.getDefault().post("noIdRetri");
        }else {
            API.retrieveRes(weightBean, new IStringResponse() {
                @Override
                public void onSuccess(String result) {
                    Log.e("success",result);
                }
                @Override
                public void onFail(int statusCode) {
                    Log.e("failure","网络连接失败,上传失败"+statusCode);
                }
            });

        }

    }

    // 6、设备状态数据接口（设备自主触发，默认半小时一次）
    public static void equipmentStatus(){
        EquipmentStatusBean equipmentStatusBean = new EquipmentStatusBean();
        equipmentStatusBean.setDeviceId(DeviceInfo.deviceId);
        equipmentStatusBean.setSignal_strength("1000");
        equipmentStatusBean.setEnvironment_temp("55");
        equipmentStatusBean.setHardware_version("2.1");
        equipmentStatusBean.setBoard_id(DeviceInfo.getBoardId());
        equipmentStatusBean.setDau_board_type("1-0,2-1,3-4");

        //返回数据{"err_code":0,"err_msg":"请求成功","data":null}
        API.equipmentStatus(equipmentStatusBean, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                String  s = result;
                Log.e("equipmentStatus","设备状态上传成功"+s);
            }

            @Override
            public void onFail(int statusCode) {
                int code = statusCode;
                Log.e("equipmentStatus","设备状态上传失败,请确认网络状态");
                EventBus.getDefault().post("sopCHud");
            }
        });
    }

    //7、事件上报接口（设备自主触发）
    public static void eventReport(String deviceId,EventReportBean eventReportBean){
        eventReportBean.setDeviceId(deviceId);
        //{"err_code":0,"err_msg":"请求成功","data":null}
        API.eventReport(eventReportBean, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                String s = result;
                JSONObject jsonObject = JSONObject.parseObject(s);
                if(jsonObject.getString("err_code").equals("0")){
                    Log.e("succ","eventReport事件上报成功");
                }
            }
            @Override
            public void onFail(int statusCode) {
                int code = statusCode;

            }
        });
    }

    //8、故障上报接口
    public static void warnReport(String deviceId,List<String> warnNum,BaseDataInfo baseDataInfo){
//        String error = warnNum[0];
//        String first = error.substring(0,1); //5
//        String end = error.substring(1); //5
//        int decimalNum = DataUtils.HexToInt(first);
//        first = StringUtil.logicRight( Integer.toBinaryString(decimalNum),4);//0101
//        end = StringUtil.logicRight( Integer.toBinaryString(DataUtils.HexToInt(end)),4); //0101
//        String all = first + end;
        String[] binarys = new String[DeviceInfo.getMouthQuantity()];
        for(int i = 0; i < DeviceInfo.getMouthQuantity();i++){
            binarys[i] = warnNum.get(i);
        }
        //{01,01,01,01}
        String mortorError = "";
        try {
            for(int i = 0 ; i < binarys.length ; i++){
                if(i == binarys.length -1){
                    if(binarys[i].equals("00")){
                        mortorError = mortorError + baseDataInfo.getData().getDeviceInList().get(i).getInner_order() + "-" +"0";
                    }else {
                        mortorError = mortorError + baseDataInfo.getData().getDeviceInList().get(i).getInner_order() + "-" +"1";
                    }
                    break;
                }
                if(binarys[i].equals("00")){
                    mortorError = mortorError + baseDataInfo.getData().getDeviceInList().get(i).getInner_order() + "-" +"0" +",";
                }else {
                    mortorError = mortorError + baseDataInfo.getData().getDeviceInList().get(i).getInner_order() + "-" +"1" +",";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            Log.e("baseData","null");
        }
        WarnReport warnReport = new WarnReport();
        warnReport.setDeviceId(deviceId);
        warnReport.setCommu_error_status("0-0");
        warnReport.setMortor_error_status(mortorError);
        warnReport.setWeigh_error_status("0-0");
        warnReport.setRangeF_error_status("0-0");
        //返回数据 {"err_code":0,"err_msg":"请求成功","data":null}
        API.warnReport(warnReport, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                String s = result;
            }

            @Override
            public void onFail(int statusCode) {
                int code = statusCode;
            }
        });
    }

    //9、管理员登陆接口
    public static void getManagerInfo(){
        UserBean userBean = new UserBean();
        userBean.setDeviceId("1");
        userBean.setUserName("admin");
        userBean.setPassword("admin");
        //返回数据  {"err_code":0,"err_msg":"请求成功","data":null}
        API.getManagerInfo(userBean, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                String s = result;
            }

            @Override
            public void onFail(int statusCode) {

                int code = statusCode;
            }
        });
    }
    //10、GPS上传
    public static void GPSInfo(GPSBean gpsBean){
        API.GPSInfo(gpsBean, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                String s = result;
                Log.d("SS","GPS上传成功");
                //关闭locationManager
                EventBus.getDefault().post("GPSSuccess");
            }

            @Override
            public void onFail(int statusCode) {
                int code = statusCode;
                Log.e("FF","GPS上传失败");
            }
        });
    }


    /******************************************************/


}
